﻿using System.Diagnostics;
using System.Web.SessionState;
using System.Web.UI;
using System.Web;
using System.Linq;

namespace System
{
  [DebuggerStepThrough]
  public static class WebExtensions
  {
    //public static T QueryValue<T>(this HtmlHelper helper, string param, T defaultValue)
    //{
    //  object value = HttpContext.Current.Request.QueryString[param] as object;
    //  if (value == null) { return defaultValue; }
    //  try
    //  {
    //    return (T)Convert.ChangeType(value, typeof(T));
    //  }
    //  catch (Exception)
    //  {
    //    return defaultValue;
    //  }
    //}

    public static T Get<T>(this HttpSessionState state, string key)
    {
      return state.Get(key, default(T));
    }
    public static T Get<T>(this HttpSessionState state, string key, T defaultValue)
    {
      var value = state[key];
      return (T)(value ?? defaultValue);
    }
    public static T Ensure<T>(this HttpSessionState state, string key) where T : class, new()
    {
      var value = state.Get<T>(key);
      if (value == null)
      {
        value = new T();
        state.Set(key, value);
      }

      return value;
    }
    public static void Set(this HttpSessionState state, string key, object value)
    {
      state[key] = value;
    }

    public static T Get<T>(this StateBag state, string key)
    {
      return state.Get(key, default(T));
    }
    public static T Get<T>(this StateBag state, string key, T defaultValue)
    {
      var value = state[key];
      return (T)(value ?? defaultValue);
    }
    public static T Ensure<T>(this StateBag state, string key) where T : class, new()
    {
      var value = state.Get<T>(key);
      if (value == null)
      {
        value = new T();
        state.Set(key, value);
      }

      return value;
    }
    public static void Set(this StateBag state, string key, object value)
    {
      state[key] = value;
    }

    public static T GetQueryString<T>(this Page state, string key, T defaultValue)
    {
      if (!HttpContext.Current.Request.QueryString.HasKeys() || !HttpContext.Current.Request.QueryString.AllKeys.Contains(key))
        return defaultValue;

      var value = HttpContext.Current.Request.QueryString[key];
      var finalVal = value.IfNullOrEmpty(defaultValue);

      return finalVal.ConvertTo<T>(defaultValue);

    }
    public static void SetQueryString(this Page state, string key, string value)
    {
      HttpContext.Current.Request.QueryString[key] = value;
    }

  }
}